package net.beyondts.mplug.listener;

import net.beyondts.mplug.PluginManager;
import net.beyondts.mplug.utils.BeanFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

/**
 * This is a listener which listens Spring's ApplicationReadyEvent, this event occurs after Spring Context refreshed.
 * In this listener, current Spring Context will be add to BeanFactory for using at anywhere, and PluginManager will load all enabled plugins.
 *
 * @author blazecrystal
 */
public class SpringReadyListener implements ApplicationListener<ApplicationReadyEvent> {
    private static Logger LOGGER = LoggerFactory.getLogger(SpringReadyListener.class);

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        BeanFactory.initByApplicationContext(event.getApplicationContext());
        try {
            BeanFactory.getBean(PluginManager.class).loadAll();
        } catch (Exception e) {
            LOGGER.error("failed to load plugins", e);
        }
    }
}
